is a React Hook that helps optimize performance by memoizing (caching) the result of a function so that it doesn't need to be recalculated on every render.useMemo
When to Use useMemo
When you have a computation that’s expensive and its result doesn’t change often, you can use useMemo to avoid recalculating it on every render.Computations:
When passing objects or arrays as props to child components, useMemo can help ensure that the references to these props remain stable, avoiding unnecessary re-renders of child components.Stable References:
Example:
import React, { useMemo } from 'react';
function MyComponent({ items }) {
// This computation will only be recalculated if `items` changes
const sumItems = useMemo(() => {
return items.reduce((sum, item) => sum + item.value, 0);
}, [items]);
return <div>Total Value: {sumItems}</div>;
}
In this example, will only be recalculated when items changes, improving performance by avoiding unnecessary calculations on every render.sumItems
You Might Also Like
Destructuring Props in Functional Components
When you pass any props to any componenet, as in this example passing name and age as props to Profi...
Optimizing Performance with React.memo
``` function MyComponent(props) { // logic goes here } export default React.memo(MyComponent); ```...